package top.milkbox.exceptionResolver;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import top.milkbox.info.R;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * mvc通用异常解析器
 */
@Slf4j
@Component
public class GeneralExceptionResolver implements HandlerExceptionResolver {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public ModelAndView resolveException(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler, Exception ex) {
        R r = new R(false, null);
        if (ex instanceof MaxUploadSizeExceededException) { // 文件大小超出上限
            log.error("文件大小超出上限");
            r.setMessage("文件大小超出上限");
            response.setContentType("application/json;charset=utf-8");
            try {
                objectMapper.writeValue(response.getOutputStream(), r);
            } catch (IOException e) {
                log.error("JSON解析或获取response输出流错误");
            }

        } else {
            log.warn("解析到其他异常，请注意");
            // 这个日志一定要加上，否则看不到报错堆栈信息
            log.error("未处理异常：" + ex, ex);

            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("errorMessage", ex.getMessage());
            modelAndView.setViewName("/error");
            return modelAndView;
        }

        // 若要返回JSON，这里要设为空
        return null;

    }
}
